﻿$(function() {
	var loading = $("#my-modal-loading");
	var loadingtext = $("#loading_text");
	var headPath = localStorage.getItem("head_image");
	$(".img_test1").attr("src", headPath); 
	var url = location.href;
	var audioServerIds = "";
	var index = 1;
	var countdown = 60;
	var isPlay = 0;
	var is_encrypt = "1";
	var pwd = "";
	var is_pay = "1";
	var type_id = "情感";
	var price;
	
	var timestamp;
	var nonceStr;
	var signature;
	var imageId1;
	var imageId2;
	var imageId3;

	var imageServerId1;
	var imageServerId2;
	var imageServerId3;

	var recordPath1;
	var recordPath2;
	var recordPath3;

	var recordServerPath1;
	var recordServerPath2;
	var recordServerPath3;

	loadingtext.text("初始化中...");
	loading.modal();
	$.ajax({
		type: "POST",
		url: "http://yx.fxtourong.com/V1/Wechat/getSignPackage",
		data: {
			token: localStorage.getItem("token"),
			url: url,
			verify: "yin@xiong8_(fx-tourong"
		},
		dataType: "json",
		success: function(data) {
			loading.modal('close');
			var code = data.code;
			if(code == "1") {
				timestamp = data.data.timestamp;
				nonceStr = data.data.nonceStr;
				signature = data.data.signature;
				wx.config({
					debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId: 'wx7f13802caf31f385', // 必填，公众号的唯一标识
					timestamp: timestamp, // 必填，生成签名的时间戳
					nonceStr: nonceStr, // 必填，生成签名的随机串
					signature: signature, // 必填，签名，见附录1
					jsApiList: ['chooseImage', 'uploadImage', 'startRecord', 'stopRecord',
						'onVoiceRecordEnd', 'playVoice', 'pauseVoice',
						'stopVoice', 'onVoicePlayEnd', 'uploadVoice',
						'downloadVoice', 'downloadImage'
					] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				});
				wx.ready(function() {
					console.log("aaaaaaaaaaaaaaaa");
					$("#openImage").click(function() {
						wx.chooseImage({
							count: 1, // 默认9
							sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
							sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
							success: function(res) {
								if(index == 1){
									onImageUp(res.localIds.toString(), 1);
									index++;
									imageId1 = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
									$("#image1").attr('src', imageId1);
									$("#openImage").css("display", "block");
									$("#image1").css("display", "inline");
								} else if (index == 2){
									onImageUp(res.localIds.toString(), 2);
									index++;
									imageId2 = res.localIds;
									$("#image2").attr('src', imageId2);
									$("#openImage").css("display", "block");
									$("#image2").css("display", "inline");
								} else if(index == 3) {
									onImageUp(res.localIds.toString(), 3);
									index++;
									imageId3 = res.localIds;
									$("#image3").attr('src', imageId3);
									$("#image3").css("display", "inline");
									$("#openImage").css("display", "none");
								}
							}
						});
					});
				});
			} else {
				alert("初始化失败:" + data.message);
			}
		},
		error:function(e){
			loading.modal('close');
			alert("初始化失败！");
		}
	});

	function onImageUp(path, index) {
		wx.uploadImage({
			localId: path, // 需要上传的图片的本地ID，由chooseImage接口获得
			isShowProgressTips: 0, // 默认为1，显示进度提示
			success: function(res) {
				if(index == 1){
					 imageServerId1 = res.serverId; // 返回图片的服务器端ID
				} else if (index == 2){
					imageServerId2 = res.serverId; // 返回图片的服务器端ID
				} else {
					imageServerId3 = res.serverId; // 返回图片的服务器端ID
				}
				
				
			}
		});
	}

	$("select#sel_pwd").change(function() {
		var sel_yn = $(this).val();
		if(sel_yn == "是") {
			$("#create_pwd").css('visibility', 'visible');
			is_encrypt = "1";
		} else {
			$("#create_pwd").css('visibility', 'hidden');
			is_encrypt = "0";
		}
	});

	$("select#sel_pay").change(function() {
		var sel_yn = $(this).val();
		if(sel_yn == "是") {
			$("#pay_text").text("付费：");
			$("#pay_text_price").css("visibility", "visible");
			is_pay = "1";
		} else {
			$("#pay_text").text("免费");
			$("#pay_text_price").css("visibility", "hidden");
			is_pay = "0";
		}
	});

	$("select#sel_type").change(function() {
		type_id = $(this).val();
	});
	
	
	
	$("#post_create_topic").click(function() {
		var topname = $("#topic_name").val();
		var topdetail = $("#topic_detail").val();
		var imageServerIds = "";
		if(imageServerId1 !== null && imageServerId1 !== undefined && imageServerId1 !== '') {
			imageServerIds = imageServerId1;
			if(imageServerId2 !== null && imageServerId2 !== undefined && imageServerId2 !== '') {
				imageServerIds = imageServerId1 + "," + imageServerId2;
				if(imageServerId3 !== null && imageServerId3 !== undefined && imageServerId3 !== '') {
					imageServerIds = imageServerId1 + "," + imageServerId2 + "," + imageServerId3;
				}
			}
		}
		if(recordServerPath1 !== null && recordServerPath1 !== undefined && recordServerPath1 !== '') {
			audioServerIds = recordServerPath1;
			if(recordServerPath2 !== null && recordServerPath2 !== undefined && recordServerPath2 !== '') {
				audioServerIds = recordServerPath1 + "," + recordServerPath2;
				if(recordServerPath3 !== null && recordServerPath3 !== undefined && recordServerPath3 !== '') {
					audioServerIds = recordServerPath1 + "," + recordServerPath2 + "," + recordServerPath3;
				}
			}
		}
		if(imageServerIds == null || imageServerIds == undefined || imageServerIds == '') {
			$("#alert_ts").text("请至少上传一张图片");
			$("#post_create_topic").attr("data-am-modal", "{target: '#my-alert'}");
			return;
		} else {
			$("#post_create_topic").removeAttr("data-am-modal");
		}
		if(audioServerIds == null || audioServerIds == undefined || audioServerIds == '') {
			$("#alert_ts").text("您还未录音");
			$("#post_create_topic").attr("data-am-modal", "{target: '#my-alert'}");
			return;
		} else {
			$("#post_create_topic").removeAttr("data-am-modal");
		}
		if(is_encrypt == "0") {
			pwd = "";
		} else {
			pwd = $("#create_pwd").val();
		}
		if(is_pay == "0") {
			price = "";
		} else {
			price = $("#create_price").val();
		}
		var store_id = localStorage.getItem("query_id");
		var urlPath = "http://yx.fxtourong.com/V1/Goods/createTopic" + "?store_id=" + store_id;
		console.log("创建话题的url:" + urlPath);
		$("#loading_text").text("提交数据中...");
		loading.modal();
		$.ajax({
			type: "POST",
			url: urlPath,
			data: {
				token: localStorage.getItem("token"),
				name: topname,
				cover: imageServerIds,
				details: topdetail,
				audio: audioServerIds,
				is_encrypt: is_encrypt,
				pwd: pwd,
				is_pay: is_pay,
				price: price,
				type_id: type_id
			},
			dataType: "json",
			success: function(data) {
				loading.modal('close');
				$("#data_json").text("2");
				console.log(data);
				var code = data.code;
				console.log(code);
				if(code == "1") {
					location.href = "../Web/query_detail.html";
				} else {
					alert(data.message + "");
				}
			},
			error: function(e){
				loading.modal('close');
				alert("服务请求异常！");
			}
		});
	});

	$("#a_openbtn").click(function() {
		if(recordPath3 !== null && recordPath3 !== undefined && recordPath3 !== '') {
			$("#alert_ts").text("最多只能录三段语音");
			$("#a_openbtn").attr("data-am-modal", "{target: '#my-alert'}");
			return;
		} else {
			$("#a_openbtn").removeAttr("data-am-modal");
		}
		$("#cancelbtn").click(function() {
			isPlay = 0;
			wx.stopRecord({
				success: function(res) {
					var localId = res.localId;
				}
			});
			countdown = 0;
			$("#openbtn").text("开始录音");
			removejscssfile("/public/yx/css/record2.css", "css");
		});
		if(isPlay == 0) {
			isPlay = 1;
			wx.startRecord();
			$('head').append('<link rel="stylesheet" href="/public/yx/css/record2.css">');
			settime();
			$("#openbtn").text("停止录音");
		} else {
			isPlay = 0;
			wx.stopRecord({
				success: function(res) {
					if(recordPath1 == null || recordPath1 == undefined || recordPath1 == '') {
						recordPath1 = res.localId;
						$("#test_listen1").css('display', 'block');
						wx.uploadVoice({
							localId: recordPath1, // 需要上传的音频的本地ID，由stopRecord接口获得
							isShowProgressTips: 0, // 默认为1，显示进度提示
							success: function(res) {
								recordServerPath1 = res.serverId; // 返回音频的服务器端ID
							}
						});
					} else if(recordPath2 == null || recordPath2 == undefined || recordPath2 == '') {
						recordPath2 = res.localId;
						$("#test_listen2").css('display', 'block');
						$("#test_listen4").css('display', 'block');
						wx.uploadVoice({
							localId: recordPath2, // 需要上传的音频的本地ID，由stopRecord接口获得
							isShowProgressTips: 0, // 默认为1，显示进度提示
							success: function(res) {
								recordServerPath2 = res.serverId; // 返回音频的服务器端ID
							}
						});
					} else {
						recordPath3 = res.localId;
						$("#test_listen3").css('display', 'block');
						wx.uploadVoice({
							localId: recordPath3, // 需要上传的音频的本地ID，由stopRecord接口获得
							isShowProgressTips: 0, // 默认为1，显示进度提示
							success: function(res) {
								recordServerPath3 = res.serverId; // 返回音频的服务器端ID
							}
						});
					}
				}
			});
			countdown = 0;
			$("#openbtn").text("开始录音");
			removejscssfile("/public/yx/css/record2.css", "css");

		}
	});

	$("#btn_listen4").click(function() {
		var audioServerIds = "";
		if(recordServerPath1 !== null && recordServerPath1 !== undefined && recordServerPath1 !== '') {
			audioServerIds = recordServerPath1;
			if(recordServerPath2 !== null && recordServerPath2 !== undefined && recordServerPath2 !== '') {
				audioServerIds = recordServerPath1 + "," + recordServerPath2;
				if(recordServerPath3 !== null && recordServerPath3 !== undefined && recordServerPath3 !== '') {
					audioServerIds = recordServerPath1 + "," + recordServerPath2 + "," + recordServerPath3;
				}
			}
		}
		
		loading.modal();
		//		$("#audio").text("语音ids:" + audioServerIds);
		$.ajax({
			type: "POST",
			url: 'http://yx.fxtourong.com/V1/Base/mergeAudio',
			data: {
				token: localStorage.getItem("token"),
				media_id: audioServerIds
			},
			dataType: "json",
			success: function(data) {
				loading.modal('close');
				var code = data.code;
				console.log(code);
				if(code == "1") {
					var audioPath = data.data;
					//						$("#btn_listen4").removeAttr("data-am-modal");
					$("#test_listen1").css('display', 'none');
					$("#test_listen2").css('display', 'none');
					$("#test_listen3").css('display', 'none');
					$("#test_listen4").css('display', 'none');
					$("#test_listen5").css('display', 'block');
					//						$("#test_listen5").append(" <audio controls='controls'>" + "<source src='../../../../" + audiop[1] + " type='audio/mpeg'>" + "</audio>");
					$("#test_listen5").append(" <audio controls='controls'>" + "<source src='" + audioPath + "'" + +" type='audio/mpeg'>" + "</audio>");
				}
			}
		});
	});

	$("#test_listen1").click(function() {
		//		$('head').append('<link rel="stylesheet" href="/public/yx/css/record2.css">');
		var stre = document.getElementById("btn_listen1").innerText;
		var recordStr = "试听1";
		wx.onVoicePlayEnd({
			success: function(res) {
				var localId = res.localId; // 返回音频的本地ID
				removejscssfile("/public/yx/css/create_tp_listen_test2.css", "css");
				$("#btn_listen1").text("试听1");
			}
		});
		if(stre == recordStr) {
			$('head').append('<link rel="stylesheet" href="/public/yx/css/create_tp_listen_test2.css">');
			$("#btn_listen1").text("结束");
			wx.playVoice({
				localId: recordPath1 // 需要播放的音频的本地ID，由stopRecord接口获得

			});

		} else {
			removejscssfile("/public/yx/css/create_tp_listen_test2.css", "css");
			$("#btn_listen1").text("试听1");
			wx.stopVoice({
				localId: recordPath1 // 需要停止的音频的本地ID，由stopRecord接口获得

			});
			//			removejscssfile("/public/yx/css/record2.css", "css");

		}

	});

	$("#test_listen2").click(function() {
		//		$('head').append('<link rel="stylesheet" href="/public/yx/css/record2.css">');
		var stre = document.getElementById("btn_listen2").innerText;
		var recordStr = "试听2";
		wx.onVoicePlayEnd({
			success: function(res) {
				removejscssfile("/public/yx/css/create_tp_listen_test2.css", "css");
				var localId = res.localId; // 返回音频的本地ID
				$("#btn_listen2").text("试听2");
			}
		});
		if(stre == recordStr) {
			$('head').append('<link rel="stylesheet" href="/public/yx/css/create_tp_listen_test2.css">');
			$("#btn_listen2").text("结束");
			wx.playVoice({
				localId: recordPath2 // 需要播放的音频的本地ID，由stopRecord接口获得

			});

		} else {
			removejscssfile("/public/yx/css/create_tp_listen_test2.css", "css");
			$("#btn_listen2").text("试听2");
			wx.stopVoice({
				localId: recordPath2 // 需要停止的音频的本地ID，由stopRecord接口获得

			});
			//			removejscssfile("/public/yx/css/record2.css", "css");

		}

	});

	$("#test_listen3").click(function() {
		//		$('head').append('<link rel="stylesheet" href="/public/yx/css/record2.css">');
		var stre = document.getElementById("btn_listen3").innerText;
		var recordStr = "试听3";
		wx.onVoicePlayEnd({
			success: function(res) {
				removejscssfile("/public/yx/css/create_tp_listen_test2.css", "css");
				var localId = res.localId; // 返回音频的本地ID
				$("#btn_listen3").text("试听3");
			}
		});
		if(stre == recordStr) {
			$('head').append('<link rel="stylesheet" href="/public/yx/css/create_tp_listen_test2.css">');
			$("#btn_listen3").text("结束");
			wx.playVoice({
				localId: recordPath3 // 需要播放的音频的本地ID，由stopRecord接口获得

			});

		} else {
			removejscssfile("/public/yx/css/create_tp_listen_test2.css", "css");
			$("#btn_listen3").text("试听3");
			wx.stopVoice({
				localId: recordPath3 // 需要停止的音频的本地ID，由stopRecord接口获得

			});
			//			removejscssfile("/public/yx/css/record2.css", "css");

		}

	});

	function settime() {
		if(countdown == 0) {
			countdown = 60;
			$("#timecount").text(60);
			return;
		} else {
			$("#timecount").text(countdown);
			countdown--;
		}
		setTimeout(function() {
			settime()
		}, 1000)
	}

});

function removejscssfile(filename, filetype) {
	var targetelement = (filetype == "js") ? "script" : (filetype == "css") ? "link" : "none"
	var targetattr = (filetype == "js") ? "src" : (filetype == "css") ? "href" : "none"
	var allsuspects = document.getElementsByTagName(targetelement)
	for(var i = allsuspects.length; i >= 0; i--) {
		if(allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename) != -1)
			allsuspects[i].parentNode.removeChild(allsuspects[i])
	}
}